import 'package:bruno/bruno.dart';
import 'package:dart_date/dart_date.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/time_range_picker.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_bottom_picker.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_site_tags.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/gun_charging_type.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/debounce_utils.dart';
import 'package:yt_devops/utils/enums.dart';

/**
 *
 * @Description TODO
 * @Author liuer
 * @CreateTime 2024年03月07日 11:11
 */
class ChargeOrderWidget extends StatefulWidget {
  final int? deviceId;
  const ChargeOrderWidget(this.deviceId,{super.key});


  @override
  State<ChargeOrderWidget> createState() => _ChargeOrderWidgetState();
}

class _ChargeOrderWidgetState extends State<ChargeOrderWidget> {
  BrnSearchTextController searchController = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  String startChargeSeqOrCarVin = '';
  String startTime = '';
  String endTime = '';
  String postStartTime = '';
  String postEndTime = '';
  String nowTime = '';
  bool isLoading = false;
  List<dynamic> orderList = [];
  int currentPage = 1;
  int pageSize = 10;
  RefreshController refreshController = RefreshController(initialRefresh: false);
  DeviceServices deviceServices = DeviceServices();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    var time = DateTime.now();
    nowTime = time.toString().substring(0,10);
    postStartTime = '$nowTime 00:00:00';
    postEndTime = '$nowTime 23:59:59';
    startTime = nowTime;
    endTime = nowTime;
    if(widget.deviceId!= null){
      _getOrderList();
    }

  }


  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        DecoratedBox(
          decoration: const BoxDecoration(color: Colour.white),
          child: Row(
            children: [
              Expanded(
                  child: BrnSearchText(
                maxHeight: 54,
                innerPadding: const EdgeInsets.fromLTRB(16, 8, 15, 8),
                hintStyle: TextStyles.lf16,
                textStyle: TextStyles.f16,
                    innerColor: Colour.backgroundColor,
                textInputType: TextInputType.number,
                searchController: searchController,
                controller: textController,
                hintText:  ResKey.enterOrderNumber.tr,
                onTextCommit: (content) => commit(content),
                onTextClear: () {
                  commit('');
                  return false;
                },
                onTextChange: DebounceUtils.debounceInput(
                    (p0) => commit(p0), 400),
              )),
              InkWell(
                onTap: () => toFilter(context),
                child: Padding(
                  padding: EdgeInsets.fromLTRB(5.w, 0, 17.w, 0),
                  child: Image.asset(
                    ImageAssets.iconFilter,
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
              )
            ],
          ),
        ),
        Gaps.vGap16,
        Expanded(
          child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              controller: refreshController,
              onRefresh: onRefresh,
              onLoading: onLoading,
              header: ListTips.classicHeader,
              footer: ListTips.generateClassicFooter,
              child: orderList.isEmpty&& isLoading ?  ListEmptyWidget(topPosition: 82):ListView.builder(
                padding: EdgeInsets.zero,
                itemBuilder: (BuildContext context, int index) {
                  return _buildItem(index);
                },
                itemCount: orderList.length,
              )),
        ),
      ],
    );
  }

  ///刷新
  void onRefresh() async {
    Log.d('onRefresh==');
    currentPage = 1;
    _getOrderList();
  }
  ///加载更多
  void onLoading() async {
    currentPage++;
    _getOrderList();
  }
  ///获取充电枪订单列表
  _getOrderList() async {
    var param = {
      'deviceId': widget.deviceId,
      'startChargeSeqOrCarVin': startChargeSeqOrCarVin,
      'startTime':  postStartTime,
      'endTime': postEndTime,
      'type':1
    };
    Log.d('param===' + param.toString());
    showLoading(toast: ResKey.loading.tr);
    var result = await deviceServices.getGunOrderList(param, onError: (error) {
      dismissLoading();
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      return false;
    });
    dismissLoading();
    isLoading = true;
    refreshController.loadComplete();
    refreshController.refreshCompleted();
    if (result != null) {
      var list = result['list'] ?? [];
      if (currentPage == 1) {
        orderList.clear();
      }
      orderList.addAll(list);
      if (result['total'] != null && result['total'] <= orderList.length) {
        refreshController.loadNoData();
      }
      setState(() {

      });
    }
  }
  _buildItem(int index){
    Map map =  orderList[index];
   return MyGestureDetector(
        onTap: (){
            Get.toNamed(RouterPath.chargeOrderDetail,arguments: {'orderDetail':map});
        },
        child:
            Container(
              margin: EdgeInsets.only(left: 16.w,right: 16.w,bottom: 10),
              padding: const EdgeInsets.only(bottom: 10,top: 10),
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))
              ),
              // height: 156 + 53 + 50,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    margin: EdgeInsets.only(left: 16.w,bottom: 16,top: 16),
                    // height: 53,
                    child: Text('${ResKey.orderNumber.tr}：${map['startChargeSeq'] != null ?map['startChargeSeq'].toString():'--'}',style: ytTextStyle(
                        color: Colour.mainTextColor,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
                    ),
                  ),
                  _rowItem('${ResKey.chargeType.tr}：', GunCharging.getChargingType(map)),
                  Gaps.vGap4,
                  _rowItem('${ResKey.chargeStrategy.tr}：', GunCharging.getChargingStrategy(map)),
                  Gaps.vGap4,
                  _rowItem('${ResKey.chargeStartTime.tr}：', map['startTime'] != null ?map['startTime'].toString():'--'),
                  Gaps.vGap4,
                  _rowItem('${ResKey.chargeEndTime.tr}：', map['endTime'] != null ?map['endTime'].toString():'--'),
                  Gaps.vGap4,
                  _rowItem('${ResKey.carVin.tr}：', map['carVin'] != null ?map['carVin'].toString():'--'),
                  Gaps.vGap4,
                  _rowItem('${ResKey.chargeTotalPower.tr}:', map['totalPower'] != null ?map['totalPower'].toString():'--'),
                  Gaps.vGap4,
                  _rowItem('${ResKey.chargeTotalFee.tr}：', map['totalMoney'] != null ?map['totalMoney'].toString():'--'),

                ],
              ),
            ),
    );
  }

  _rowItem(String title,String value){
    return   Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Container(
          width: 98.w,
          // height: 40,
          color: Colors.white,
          margin: const EdgeInsets.only(left: 16),
          child: Text(
            maxLines: 2,
            title,
            style: ytTextStyle(
                color: Colour.lightTextColor,
                fontSize: 14,
                fontWeight: FontWeight.normal),
          ),
        ),

        SizedBox(
          height: 20,
          child: Text(
            value,
            style: ytTextStyle(
                color: Colour.mainTextColor,
                fontSize: 14,
                fontWeight: FontWeight.normal),
          ),
        ),
      ],
    );
  }
  toFilter(BuildContext context) {
    ///点击按钮隐藏键盘
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    ytBottomPicker(context, mainButtonOnTap: () {
      // onRefresh(refereshType: RefereshType.initial);
      Log.d('confirm');
      _getOrderList();
      Get.back();
    },minHeight:250, resetTap: (setstate) {
      reset(setstate);
    }, builder: (context) {
      return  StatefulBuilder(
          builder: (context, setState) => Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TimeRangePicker(
                title: ResKey.creationTime.tr,
                padding: EdgeInsets.only(right: 16.w),
                startTime: startTime,
                endTime: endTime,
                onChange: (start, end) {
                  startTime = start.replaceAll('/', '-');
                  endTime = end.replaceAll('/', '-');
                  Log.d('startTime===' + startTime);
                  Log.d('startTime===' + startTime);
                  postStartTime = '$startTime 00:00:00';
                  postEndTime = '$endTime 23:59:59';
                },
              ),
              SizedBox(
                height: 3.h,
              ),
            ],
          ),
      );
    });
  }

  commit(String content) {
    startChargeSeqOrCarVin = content;
    _getOrderList();
  }

  reset(void Function(void Function()) setState) {
    startTime = '';
    postStartTime ='';
    postEndTime = '';
    endTime = '';
    setState(() {});
  }
}
